//给定一个二叉树，返回它的 后序 遍历。 
//
// 示例: 
//
// 输入: [1,null,2,3]  
//   1
//    \
//     2
//    /
//   3 
//
//输出: [3,2,1] 
//
// 进阶: 递归算法很简单，你可以通过迭代算法完成吗？ 
// Related Topics 栈 树 
// 👍 354 👎 0

package leetcode.editor.cn;

import common.bean.TreeNode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * Java：二叉树的后序遍历
 * 
 * @author changgui
 */
@SuppressWarnings("all")
public class P145_BinaryTreePostorderTraversal {
    public static void main(String[] args) {
        Solution solution = new P145_BinaryTreePostorderTraversal().new Solution();
        // TODO 此处开始你的表演
        
    }


    //leetcode submit region begin(Prohibit modification and deletion)
    /**
     * 递归
     */
    //class Solution {
    //    public List<Integer> postorderTraversal(TreeNode root) {
    //        List<Integer> list = new ArrayList<>();
    //        postorderTraversal(list, root);
    //        return list;
    //    }
    //
    //    private void postorderTraversal(List<Integer> list, TreeNode root) {
    //        if (root == null) {
    //            return;
    //        }
    //        postorderTraversal(list, root.left);
    //        postorderTraversal(list, root.right);
    //        list.add(root.val);
    //    }
    //}
    /**
     * 迭代, 二次标记法
     * 时间复杂度 O(n)
     */
    class Solution {
        public List<Integer> postorderTraversal(TreeNode root) {
            List<Integer> list = new ArrayList<>();
            if (root == null) {
                return list;
            }
            Deque<TreeNodeHelper> deque = new ArrayDeque<>();
            deque.push(new TreeNodeHelper(root));
            TreeNodeHelper tnhTemp;
            while (!deque.isEmpty()) {
                tnhTemp = deque.pop();
                if (tnhTemp.treeNode == null) {
                    continue;
                }
                if (tnhTemp.times == 2) {
                    list.add(tnhTemp.treeNode.val);
                    continue;
                }
                // 根据后序遍历 左-右-中 此处入栈顺序 中-右-左
                // 可增加为空不入栈判断，此处为了方便理解不做判断
                deque.push(tnhTemp.incr());
                deque.push(new TreeNodeHelper(tnhTemp.treeNode.right));
                deque.push(new TreeNodeHelper(tnhTemp.treeNode.left));
            }
            return list;
        }
    }

    class TreeNodeHelper {
        public TreeNode treeNode;
        public int times;

        public TreeNodeHelper(TreeNode treeNode) {
            this.treeNode = treeNode;
            this.times = 1;
        }

        public TreeNodeHelper incr() {
            this.times = 2;
            return this;
        }
    }
    //leetcode submit region end(Prohibit modification and deletion)
}
